import * as fse from 'fs-extra';
import path from 'path';

import { getJson5Obj } from '../../../../src/utils/json-util';
import { runHvigorAsync } from '../../common/common';
import {
  AbilityType,
  APIType,
  APIVersion, CaseLevel,
  LanguageType, ModuleTemplateType,
  RuntimeOSType,
  SDKType
} from '../../plugins/project-builder/models/constants';
import { TestCaseBuilder } from '../../plugins/task-builder/task-case-builder';
import { ProjectBuildOption, TestCaseFun } from '../../plugins/task-builder/test-case';
import { TestTaskOptionBuilder } from '../../plugins/task-builder/test-task-option';


const projectBuilderOption: ProjectBuildOption = {
  template: {
    sdk: SDKType.Single,
    runtimeOS: RuntimeOSType.HarmonyOS,

    // 当前都是5.0 api已经不用管
    apiVersion: APIVersion.API11,
    apiType: APIType.STAGE,
    language: LanguageType.ArkTs,
    abilityType: AbilityType.Application,
    entryTemplateType: ModuleTemplateType.EmptyAbility
  }
};

// 可视化命令行构建优先级问题,analyze字段生效的顺序，命令行参数/settings > hvigor-config
const testfun: TestCaseFun = async (project, taskConfig, record) => {
  const rootPath = project.projectRootPath();
  const hvigorConfigPath = path.resolve(rootPath, 'hvigor', 'hvigor-config.json5');
  const hvigorConfigObj =  getJson5Obj(hvigorConfigPath);

  // 1、修改模板中hvigor-config中的analyze为normal  在命令行执行时配置analyze为false校验优先级顺序
  hvigorConfigObj.execution = {
    "analyze": "normal"
  };
  fse.writeFileSync(hvigorConfigPath, JSON.stringify(hvigorConfigObj));
  const commands: string[] = 'assembleHap --analyze=false'.split(' ');
  const result = await runHvigorAsync(project.projectRootPath(), commands);
  record.addStep('初始构建hap', result);
  expect(result.stdout).toContain('BUILD SUCCESSFUL');

  // 2、 判断是否生成了report目录,由于命令行中的analyze为false生效所以不应该生成report
  const reportPath = path.resolve(rootPath, '.hvigor', 'report');
  expect(fse.existsSync(reportPath)).toEqual(false);

  // 3、删除higorConfig中配置的analyze配置项和命令行中的analyze并执行构建
  hvigorConfigObj.execution = {};
  fse.writeFileSync(hvigorConfigPath, JSON.stringify(hvigorConfigObj));
  const commandNoAnalyze: string[] = 'assembleHap'.split(' ');
  const resultNoAnalyze = await runHvigorAsync(project.projectRootPath(), commandNoAnalyze);
  record.addStep('初始构建hap', resultNoAnalyze);
  expect(resultNoAnalyze.stdout).toContain('BUILD SUCCESSFUL');

  // 4、 判断是否生成了report日志,由于该场景下命令行和hvigor-config都没有配置所以会生成default默认的report日志
  const reportFiles = fse.readdirSync(reportPath);
  expect(reportFiles.length).toBeGreaterThan(0);
};

TestCaseBuilder.builder()
  .caseName('DTS2024070104310')
  .description('可视化命令行构建优先级问题')
  .projectBuilderOption(projectBuilderOption)
  .taskConfig(TestTaskOptionBuilder.builder().caseLevel(CaseLevel.DTS).build())
  .testFun(testfun)
  .load();